package com.pdd.account.tourist.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pdd.account.tourist.enums.WebResultEmun;
import com.pdd.account.tourist.response.ResponseResult;
import com.pdd.account.tourist.server.commons.util.MailUtil;
import com.pdd.account.tourist.server.commons.util.RandomValidateCodeUtil;
import com.pdd.account.tourist.server.commons.yml.UserConfig;
import com.pdd.account.tourist.server.mapper.Blog_AccountMapper;
import com.pdd.account.tourist.server.service.Blog_AccountService;
import com.pdd.account.tourist.server.service.Blog_Login_LogService;
import com.pdd.commons.entity.dao.Blog_Account;
import com.pdd.commons.entity.dto.LoginForm;
import com.pdd.commons.entity.dto.RegisterForm;
import com.pdd.commons.entity.vo.AccountInfo_Vo;
import com.pdd.commons.entity.vo.UserIndex_Vo;
import com.pdd.commons.response.ResponseEntity;
import com.pdd.commons.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author:liyangpeng
 * @date:2019/6/21 16:07
 */
@Service
@Slf4j
public class Blog_AccountServiceImpl implements Blog_AccountService {

    @Autowired
    private Blog_AccountMapper blog_accountMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private Blog_Login_LogService blog_login_logService;
    @Autowired
    private AccountUtil accountUtil;
    @Autowired
    private UserConfig userConfig;
    @Autowired
    private MailUtil mailUtil;
    @Autowired
    private WebAreaUtil webAreaUtil;

    @Override
    public ResponseEntity login(LoginForm loginForm) {
        QueryWrapper queryWrapper=new QueryWrapper<>().eq("account",loginForm.getAccount());
        Blog_Account blog_account=blog_accountMapper.selectOne(queryWrapper);
        //如果账号存在则匹配密码blog_account
        if(blog_account!=null){
            //反写加密密码
            String pwd= DigestUtils.md5DigestAsHex((loginForm.getPassword()+blog_account.getRegistTime().getTime()+ PublicKey.PWD_SALTVALUE).getBytes());
            if(!blog_account.getPassword().equals(pwd)){
                //账号或密码错误
                return ResponseResult.Return(WebResultEmun.ACCOUNT_OR_PASSWORD_ERROR);
            }
            //登录成功【1.生成cookie信息 2.服务端保留登录信息 3.返回cookie到前端】
            Long login_time=System.currentTimeMillis();
            //sessionId生成规则
            String sessionKey=loginForm.getAccount()+"_"+DigestUtils.md5DigestAsHex((loginForm.getPassword()+login_time).getBytes());
            //返回cookie信息到前台
            blog_account.setSession_id(sessionKey);
            //登录信息保留到redis
            redisUtils.stringSetString(sessionKey,JSON.toJSONString(blog_account));
            //保留登录信息2小时
            redisUtils.setExpire(sessionKey,2L, TimeUnit.HOURS);
            blog_login_logService.addLog(blog_account.getId(),loginForm.getPlatform(),login_time);
            //记录登录日志
            return ResponseResult.Return(WebResultEmun.ACCOUNT_LOGIN_SUCCESS,blog_account);
        }
        return ResponseResult.Return(WebResultEmun.ACCOUNT_NOT_EXISTS_ERROR);
    }

    @Override
    public ResponseEntity getUserIndexData(Integer author_id) {
        Integer self_author_id=0;
        AccountInfo_Vo accountInfo_vo=accountUtil.getLoginInfo();
        if(accountInfo_vo!=null){
            self_author_id=accountInfo_vo.getId();
        }
        UserIndex_Vo userIndex_vo=blog_accountMapper.getUserIndexData(author_id,self_author_id);
        //如果存在用户则计算其经验值
        if(userIndex_vo!=null){
            userIndex_vo.setNextLevelExp(accountUtil.getlevelExp(userIndex_vo.getLevel()));
        }
        return ResponseResult.Return(userIndex_vo);
    }

    @Override
    public ResponseEntity register(RegisterForm registerForm) {
        //验证验证码
        String cache_code=redisUtils.stringGetStringByKey(PublicKey.REGISTER_EMAIL_PREFIX+registerForm.getEmail());
        if(StringUtils.isEmpty(cache_code)||!cache_code.equals(registerForm.getCode())){
            return ResponseResult.Return(WebResultEmun.REGISTER_CODE_ERROR);
        }
        //1.验证账号
        Long validAccount =blog_accountMapper.validAccount(registerForm.getAccount());
        if(validAccount!=null&&validAccount>0){
            return ResponseResult.Return(WebResultEmun.REGISTER_ACCOUNT_EXISTS);
        }
        //2.验证昵称
        Long validNickName =blog_accountMapper.validNiciName(registerForm.getNickName());
        if(validNickName!=null&&validNickName>0){
            return ResponseResult.Return(WebResultEmun.REGISTER_NICKANME_EXISTS);
        }
        //3.验证邮箱
        Long validEmail =blog_accountMapper.validEmail(registerForm.getEmail());
        if(validEmail!=null&&validEmail>0){
            return ResponseResult.Return(WebResultEmun.REGISTER_EMAIL_EXISTS);
        }
        Blog_Account blog_account=new Blog_Account();
        //4.加密密码(加密规则:原密码+注册时间+盐值MD5确保同密码不一致)
        long registerTime=System.currentTimeMillis();
        BeanUtils.copyProperties(registerForm,blog_account);
        HttpServletRequest request=webAreaUtil.getRequest();
        String md5pwd=DigestUtils.md5DigestAsHex((registerForm.getPassword()+registerTime+PublicKey.PWD_SALTVALUE).getBytes());
        blog_account.setPassword(md5pwd);
        blog_account.setAvatar(userConfig.getAvatar());
        blog_account.setBackImg(userConfig.getBackImg());
        blog_account.setRegistIp(UserAgentUtils.getIp(request));
        blog_account.setRegistDevice(UserAgentUtils.getOsName(request));
        blog_account.setPerSign("这个人很懒,什么也没留下.");
        blog_account.setRegistTime(new Date(registerTime));
        boolean addSuccess=blog_account.insert();
        if(!addSuccess){
            return ResponseResult.Return(WebResultEmun.REGISTER_ERROR);
        }
        return ResponseResult.Return(WebResultEmun.REGISTER_SUCCESS);
    }

    @Override
    public ResponseEntity sendMailValidCode(Map<String,String> param) {
        String email=param.get("email");
        if(StringUtils.isEmpty(email)){
            return ResponseResult.RETURN_ERROR("邮箱地址不能为空");
        }
        //防止刷邮箱验证码,ip 跟邮箱双重验证
        HttpServletRequest request=webAreaUtil.getRequest();
        String ip=UserAgentUtils.getIp(request);
        String ipResult=redisUtils.stringGetStringByKey(PublicKey.REGISTER_EMAIL_PREFIX+ip);
        if(!StringUtils.isEmpty(ipResult)){
            return ResponseResult.RETURN_ERROR("您点的太快了,休息一下再来吧");
        }
        //邮箱限制防止重新发送验证码
        String emailResult=redisUtils.stringGetStringByKey(PublicKey.REGISTER_EMAIL_PREFIX+email);
        if(!StringUtils.isEmpty(emailResult)){
            return ResponseResult.RETURN_ERROR("您点的太快了,休息一下再来吧");
        }
        //验证码生成规则
        String code= RandomValidateCodeUtil.getRandomCode(4);
        //存放redis
        ResponseEntity result=mailUtil.sendMailValidCode(email,"gay哩gay气-邮箱验证",code);
        if(result.isSuccess()){
            //验证码存放redis
            redisUtils.stringSetValueAndExpireTime(PublicKey.REGISTER_EMAIL_PREFIX+email,code,90);
            //ip也存放redis
            redisUtils.stringSetValueAndExpireTime(PublicKey.REGISTER_EMAIL_PREFIX+ip,email,90);
        }
        return result;
    }
}
